<!-- frontend/src/components/User.vue -->
<template>
	<div class="user-manager">
		<div class="query-form">
			<!-- 添加ref属性 -->
			<el-form inline :model="user" ref="formRef">
				<el-form-item label="用户ID" prop="userId">
					<el-input v-model="user.userId" placeholder="请输入用户ID" />
				</el-form-item>
				<el-form-item label="用户名称" prop="userName">
					<el-input v-model="user.userName" placeholder="请输入用户名称" />
				</el-form-item>
				<el-form-item label="用户状态" prop="state">
					<el-select v-model="user.state">
						<el-option :value="0" label="所有"></el-option>
						<el-option :value="1" label="在职"></el-option>
						<el-option :value="2" label="离职"></el-option>
						<el-option :value="3" label="试用期"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery">查询</el-button>
					<!-- handleReset 传参 -->
					<el-button @click="handleReset(formRef)">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="base-table">
			<div class="action">
				<el-button type="primary" @click="addUser">新增</el-button>
				<el-button type="danger" @click="multiDelete">批量删除</el-button>
			</div>
			<el-table @selection-change="handleSelectionChange" :data="userList" style="width: 100%">
				<el-table-column type="selection" width="30" />
				<el-table-column
					v-for="item in columns"
					:key="item.prop"
					:prop="item.prop"
					:label="item.label"
					:width="item.width"
					:formatter="item.formatter"
				/>
				<el-table-column fixed="right" label="操作" width="140">
					<template #default="scope">
						<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button
							:disabled="scope.row.state === 2"
							type="danger"
							@click="handleDelete(scope.row.userId)"
							size="small"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				hide-on-single-page
				class="pagination"
				small
				:page-size="pager.pageSize"
				background
				layout="prev, pager, next"
				:total="pager.total || 0"
				@current-change="handleCurrentChange"
			/>
		</div>
		<el-dialog :title="actionName + '用户'" v-model="showModal" :before-close="dialogClose">
			<!-- 表达对象的引用, 将来可以通过dialogForm进行表单的验证 -->
			<!-- userForm 给表单绑定事件 -->
			<!-- label-width 设置表单宽度 -->
			<!-- rules 表单数据的校验规则 -->
			<el-form ref="dialogForm" :model="userForm" label-width="100px" :rules="rules">
				<!-- label 中文名 -->
				<!-- prop model 的键名, prop 对应数据的属性名, 表单校验时, 必填 -->
				<el-form-item label="用户名" prop="userName">
					<!-- 绑定数据为userForm.userName -->
					<!-- 判断如果当前操作为编辑, edit, 用户名称不可操作 -->
					<el-input v-model="userForm.userName" :disabled="action === 'edit'" placeholder="请输入用户名称" />
				</el-form-item>
				<el-form-item label="邮箱" prop="userEmail">
					<el-input v-model="userForm.userEmail" :disabled="action === 'edit'" placeholder="请输入用户邮箱">
						<template #append>@wangshidai.com</template>
					</el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="mobile">
					<el-input v-model="userForm.mobile" placeholder="请输入手机号" />
				</el-form-item>
				<el-form-item label="岗位" prop="job">
					<el-input v-model="userForm.job" placeholder="请输入岗位" />
				</el-form-item>
				<el-form-item label="状态" prop="state">
					<el-select v-model="userForm.state">
						<el-option :value="1" label="在职"></el-option>
						<el-option :value="2" label="离职"></el-option>
						<el-option :value="3" label="试用期"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="系统角色" prop="roleList">
					<!-- multiple, 代表可多选 -->
					<el-select v-model="userForm.roleList" placeholder="请选择用户系统角色" multiple style="width: 100%">
						<el-option v-for="role in roleList" :key="role._id" :label="role.roleName" :value="role._id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="部门" prop="deptId">
					<!-- 级联选择器, 需要给options传递一个数组 -->
					<!-- checkStrictly true 父子节点取消选中关联 -->
					<!-- value: '_id', label: 'deptName' 显示对应字段的值, 类似字段映射 -->
					<el-cascader
						v-model="userForm.deptId"
						placeholder="请选择所属部门"
						:options="deptList"
						:props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
						clearable
						style="width: 100%"
					></el-cascader>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose(dialogForm)">取 消</el-button>
					<el-button type="primary" @click="handleSubmit(dialogForm)">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script setup>
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import api from "@/api";
import util from "@/utils/util";
import { ElMessage } from "element-plus";
// 搜索栏数据
const user = reactive({
	state: 1,
});
// 新增用户Form对象
const userForm = reactive({
	state: 3,
});
const userList = ref([]);
const pager = ref({});
// 所有角色列表
const roleList = ref([]);
// 所有部门列表
const deptList = ref([]);
// 定义用户操作行为
const action = ref("add");
const actionName = ref("添加");
// 对话框相关
const showModal = ref(false);
const formLabelWidth = "100px";
const form = reactive({
	name: "",
	region: "",
	date1: "",
	date2: "",
	delivery: false,
	type: [],
	resource: "",
	desc: "",
});
// 选中的用户id
const checkedUserIds = ref([]);
// 表单引用
const formRef = ref();
const dialogForm = ref();
const columns = reactive([
	{
		label: "用户ID",
		prop: "userId",
		width: "70",
	},
	{
		label: "用户名",
		prop: "userName",
		width: "140",
	},
	{
		label: "用户邮箱",
		prop: "userEmail",
	},
	{
		label: "用户角色",
		prop: "role",
		width: "85",
		formatter(row, column, value) {
			const roleObject = {
				0: "管理员",
				1: "普通用户",
			};
			return roleObject[value];
		},
	},
	{
		label: "用户状态",
		prop: "state",
		width: "85",
		formatter(row, column, value) {
			const roleObject = {
				1: "在职",
				2: "离职",
				3: "试用期",
			};
			return roleObject[value];
		},
	},
	{
		label: "注册时间",
		prop: "createTime",
		width: "135",
		formatter(row, column, value) {
			return util.utc2beijing(value);
		},
	},
	{
		label: "最后登录时间",
		prop: "lastLoginTime",
		width: "135",
		formatter(row, column, value) {
			return util.utc2beijing(value);
		},
	},
]);
const rules = reactive({
	userName: [
		{
			required: true,
			message: "请输入用户名称",
			trigger: "blur",
		},
	],
	userEmail: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
	mobile: [
		{
			pattern: /1[3-9]\d{9}/,
			message: "请输入正确的手机号格式",
			trigger: "blur",
		},
	],
	deptId: [
		{
			required: true,
			message: "请输入用户邮箱",
			trigger: "blur",
		},
	],
});
// 组件挂载之后触发
onMounted(() => {
	// 获取用户列表
	getUserList();
	// 获取部门列表
	getDeptList();
	// 获取角色列表
	getRoleList();
});
// 点击右上角的×, 关闭对话框
function dialogClose() {
	handleClose(dialogForm.value);
}

function getDeptList() {
	api.getDeptList().then((res) => {
		console.log(res);
		deptList.value = res;
	});
}
function getRoleList() {
	api.getRoleAllList().then((res) => {
		console.log(res);
		roleList.value = res;
	});
}
// 点击弹框的取消按钮
function handleClose(formEl) {
	// 重置表单
	handleReset(formEl);
	// 关闭弹框
	showModal.value = false;
}
function handleSubmit(formRef) {
	formRef.validate((valid) => {
		// 如果结果为true
		if (valid) {
			console.log("正在请求新建用户接口...");
			let params = { ...toRaw(userForm), userEmail: userForm.userEmail + "@wangshidai.com" };
			params.action = action.value;
			// 提交用户信息到服务器
			api.userSubmit(params).then((res) => {
				console.log(res);
				if (res) {
					// 弹框提醒用户
					ElMessage.success(actionName.value + "用户成功!");
					// 关闭对话框
					showModal.value = false;
					// 重置表单
					handleReset(formRef);
					// 重新请求用户列表
					getUserList();
				} else {
					ElMessage.error(actionName.value + "用户失败!");
					return false;
				}
			});
		} else {
			ElMessage.error("校验表单失败");
			return false;
		}
	});
}
// 新增用户
function addUser() {
	// 修改action
	action.value = "add";
	actionName.value = action.value === "add" ? "增加" : "编辑";
	showModal.value = true;
}
// 批量删除
function multiDelete() {
	if (checkedUserIds.value.length === 0) {
		ElMessage.error("请选择要删除的用户!");
		return;
	}
	// 通过id删除用户
	const params = {
		userIds: checkedUserIds.value,
	};
	api.userDelete(params).then((res) => {
		if (res > 0) {
			ElMessage.success(`批量删除成功, 共删除${res}条!`);
			getUserList();
		} else {
			ElMessage.error("批量删除失败!");
		}
	});
}
const handleSelectionChange = (val) => {
	const arr = [];
	val.forEach((element) => {
		arr.push(element.userId);
	});
	checkedUserIds.value = arr;
};
// 获取菜单列表
function getUserList() {
	console.log(pager.value);
	// 设置参数
	const params = { ...pager.value, ...user };
	console.log(params);
	// 走ajax, 获取菜单列表
	api.userList(params).then((res) => {
		// 更新userMenu的数据
		console.log("res");
		console.log(res);
		const { list, page } = res;
		userList.value = list;
		pager.value = page;
		if (list.length === 0) {
			ElMessage.error("暂无数据!");
		}
		console.log(list.length);
	});
}
// 点击页码触发函数
const handleCurrentChange = (val) => {
	// 更新pager
	pager.value.pageNum = val;
	// 请求接口
	getUserList();
};
// 查询函数
function handleQuery() {
	// 请求接口
	getUserList();
}
// 重置函数
function handleReset(formEl) {
	formEl.resetFields();
	// 请求接口
	getUserList();
}

// 编辑函数
function handleEdit(row) {
	// 修改action
	action.value = "edit";
	actionName.value = action.value === "add" ? "增加" : "编辑";
	// 展示弹框
	showModal.value = true;
	// 展示数据到弹框
	nextTick(() => {
		Object.assign(userForm, row);
		// 清理掉邮箱的后缀, 使用正则替换, g表示匹配并且替换所有符合条件的字符串
		userForm.userEmail = userForm.userEmail.replace(/@.+$/g, "");
	});
}

// 删除用户记录
function handleDelete(userId) {
	// 执行删除逻辑, 需要先获取用户id
	console.log(userId);
	// 通过id删除用户
	const params = { userIds: [userId] };
	api.userDelete(params).then((res) => {
		if (res === 1) {
			ElMessage.success(`删除成功!`);
			// 重新获取用户列表
			getUserList();
		}
	});
}
</script>
<style></style>
